<template>
  <div class="uni-login-others">
    <div class="uni-login-others-divider" v-if="title">{{ title }}</div>
    <div class="uni-login-others-list">
      <img class="item" @click="otherLogin('facebook')" src="@/assets/images/icon_facebook.png" alt="">
      <img class="item" @click="otherLogin('google')" src="@/assets/images/icon_google.png" alt="">
    </div>
  </div>
</template>

<script>
import {exchangeToken, thirdMicroLogin} from "@/api";
import getEnv from "@/utils/env";
import Cookies from 'js-cookie';
var thirdWindow = null
let isThirdRequest = false;

export default {
  name: 'OtherLogin',
  components: {},
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    title: {
      type: String,
      default: ''
    },
      subscribe_ad: {
          type: Boolean,
          default: false
      },
    // 跳转前事件处理，返回false可阻止跳转
    beforeGo: {
      type: Function,
      default: () => true
    }
  },
  data() {
    return {
      // 判断是否已经监听 postmessage
      messageHandlerCount: 0,
      thirdWindow: null
    }
  },
  inject: ["loginSuccess"],
  watch: {},
  computed: {},
  created() {
  },
  mounted() {
  },
  methods: {
    async otherLogin(type) {
        console.log(this.subscribe_ad);
      if (!this.beforeGo()) return
      console.log(this.$root.$options);
      const {app_key, thirdLogin, mode, from, scene, platform, language, sub_channel_id, channel_id, channel_ad_id, share_code} = this.$root.$options.props;
      console.log(app_key, 'app_key');
      console.log(thirdLogin, 'thirdLogin');
      const apiHost = getEnv(mode.type) ? getEnv(mode.type).apiHost : ''
      const userCenterHost = getEnv(mode.type) ? getEnv(mode.type).userCenterHost : ''
      if (app_key.type === 'A0002') {
        // let url = ''
        const callback = `${userCenterHost}/thirdMicroLogin/index.html?app_key=${app_key.type}&platform=${platform.type}${platform.type === 'mobile' ? '&sourceUrl=' + window.btoa(location.href) : ''}&isFromUnilogin=1&scene=${scene.type}&from=${from.type}&share_code=${share_code.type}&lng=${language.type}`
        // url = `${apiHost}/v1/third/microIndex?type=${type}&from=${from.type}&share_code=${share_code.type}&scene=${scene.type}&return_url=${encodeURIComponent(callback)}`
        if (!isThirdRequest) {
          isThirdRequest = true;
          await thirdMicroLogin({
              type,
              sub_channel_id: sub_channel_id.type,
              from: from.type,
              channel_ad_id: channel_ad_id.type,
              channel_id: channel_id.type,
              share_code: share_code.type,
              app_key: 'client',
              scene: 'client',
              is_bind: false,
              return_url: encodeURIComponent(callback),
              subscribe_ad: this.subscribe_ad ? 1 : 0,
          }).then((res) => {
              if (res.code === 0) {
                  const {code, url} = res.data;
                  thirdLogin.type(code, url, type)
              }
              isThirdRequest = false;
          }).catch((e) => {
              console.log(e, '--err--')
              isThirdRequest = false;
          });
        }
      } else {
        let url = ''
        const callback = `${apiHost}/thirdlogin/index.html?app_key=${app_key.type}&platform=${platform.type}${platform.type === 'mobile' ? '&sourceUrl=' + window.btoa(location.href) : ''}&isFromUnilogin=1&scene=${scene.type}&from=${from.type}&share_code=${share_code.type}&lng=${language.type}`
        url = `${apiHost}/v1/third/index?type=${type}&from=${from.type}&share_code=${share_code.type}&scene=${scene.type}&subscribe_ad=${this.subscribe_ad ? 1 : 0}&return_url=${encodeURIComponent(callback)}`
        // 控制开启窗口
        const width = 600
        const height = 400
        const feature = `height=${height}, width=${width},toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no`;
        //
        if (this.$root.$options.props.platform.type === 'pc') {
          thirdWindow = window.open(url, type, feature);
          const messageHandler = (e) => {
            if (e.origin.includes(apiHost.split('//')[1])) {
              console.log('> 监听到三方登录postMessage:', e)
              this.loginSuccess(e.data.userData)
              // 登录组件自己不存储登录信息, 在项目中手动存储
              // this._getToken(e.data, 'login', {
              //   isAccountLogin: false
              // }, type);
              thirdWindow.close();
              thirdWindow = null;
              window.removeEventListener('message', messageHandler, false);
              this.messageHandlerCount = 0;
              console.log('> 三方登录完成')
            }
          };
          if (this.messageHandlerCount === 0) {
            window.addEventListener('message', messageHandler, false);
            this.messageHandlerCount = 1;
          }
        } else {
          window.location = url;
        }
      }
    },
    // 用统一登录的token换取业务token
    // type login | register
    _getToken(userData, type, obj, thirdType) {
      const dataToken = userData.token || userData.user_token;
      const {app_key, tokenName} = this.$root.$options.props;

      obj = obj || {
        isAccountLogin: false,
        isPhonePass: false,
        isEmailPass: false,
        isUserPass: false
      };
      if (!dataToken) return;
      this.token = dataToken;
      const getLoginType = () => {
        if (!obj.isAccountLogin) {
          if (!thirdType) {
            return 15;
          }
          const map = {
            qq: 4,
            weibo: 5,
            weixin: 3,
            wegame: 6,
            4399: 7,
            lenovo: 8,
            facebook: 9,
            google: 10,
            swjoy: 11,
            ygx: 12,
            huya: 13,
            yly: 14,
            bilibili: 16,
            douyu: 17,
            steam: 18,
            zhengqi: 19
          };
          return map[thirdType];
        }
        if (obj.isPhonePass) {
          return 1;
        }
        if (obj.isEmailPass) {
          return 2;
        }
        if (obj.isUserPass) {
          return 0;
        }
      };
      const _getUser = (token, partUserData) => {
        // 三方登录
        if (partUserData.userData) {
          partUserData = partUserData.userData;
        }
        let userData = {
          anti_level: 1,
          birthday: '',
          card_id: '',
          email: '',
          ...partUserData
        };
        /*
          接口未返回渠道信息
          从token里拿
         */
        // if (userData.channel_id === undefined) {
        //   userData = Object.assign({}, userData, this._getChannelAndAdidFromToken(token));
        // }
        const isReg = type === 'register';
        const extraData = {
          from: this.from || 'website',
          subChannel: userData.sub_channel_id,
          channel: userData.channel_id,
          channelAdId: userData.channelAdId || 0
        };
        const eventData = {
          token,
          useCookie: this.useCookie,
          userData
        };
        if (tokenName.type) {
          eventData.tokenName = tokenName.type;
        }
        if (isReg) {
          extraData.type = 2;
        } else {
          extraData.loginType = getLoginType();
        }
        // this._fire(type, eventData);
        // this._toggleShow(false);
        // this._log(
        //     {
        //       ...userData,
        //       token
        //     }
        //     , isReg ? 'reg' : type,
        //     extraData
        // );
        // this.destroy();
      };

      // 登录器需要换token
      if (app_key.type === 'A0002') {
        exchangeToken(
            {
              app_key: this.appName,
            },
            dataToken
        ).then((res) => {
          const {code, data, msg} = res || {};
          const {expire, token} = data;
          if (code === 0) {
            this._setToken(token, expire);
            _getUser(token, userData);
          } else {
            this.$message.error(msg);
          }
        })
      }
      // 网站业务不需要换token
      if (app_key.type === 'A0001') {
        this._setToken(dataToken, userData.expire);
        //
        _getUser(dataToken, userData);
      }
    },

    _setToken(token, expire) {
      const {tokenName} = this.$root.$options.props;
      if (!tokenName.type) return;
      // if (this.useCookie) {
        Cookies.set(tokenName.type, token, {
          expires: new Date(expire * 1000),
        });
      // } else {
        localStorage.setItem(tokenName.type, token);
      // }
    }

  },
  beforeDestroy() {
  }
}
</script>
<style scoped lang="scss">
.uni-login-others {
  &-divider {
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
    font-size: 12px;

    &:before,
    &:after {
      content: "";
      height: 1px;
      background-color: #fff;
      flex: 1;
    }

    &:before {
      margin-right: 10px;
    }

    &:after {
      margin-left: 10px;
    }
  }

  &-list {
    margin: 20px 0 30px;
    display: flex;
    justify-content: center;

    .item {
      display: block;
      margin: 0 24px;
      width: 55px;
      height: 55px;
      cursor: pointer;
      transition: .2s;

      &:hover {
        transform: translateY(-4px);
      }
    }
  }

}
</style>
